<template>
  <div>
    <a-layout style="min-height: 100vh; overflow: hidden">
      <a-layout-sider v-model="collapsed" collapsible @click="closeChart">
        <div class="logo" v-if="!collapsed">好溪防洪调度模拟系统</div>
        <div class="logo" v-if="collapsed">FC</div>
        <a-menu theme="dark" v-model="selectedKeys" mode="inline">
          <a-menu-item key="1">
            <router-link to="/home/map" />
            <i class="iconfont icon-shouye iconStyle"></i>
            <span style="width: 50px; text-align: left" v-if="!collapsed">首页</span>
          </a-menu-item>
          <a-menu-item key="2" v-show="isLogin">
            <router-link to="/home/rainAggregate" />
            <i class="iconfont icon-shuizha iconStyle"></i>
            <span style="width: 50px; text-align: left" v-if="!collapsed">雨量站</span>
          </a-menu-item>
          <a-menu-item key="3" v-show="isLogin">
            <router-link to="/home/lockStation" />
            <i class="iconfont icon-jianyiyuliangzhan iconStyle"></i>
            <span style="width: 50px; text-align: left" v-if="!collapsed">闸站</span>
          </a-menu-item>
        </a-menu>
      </a-layout-sider>
      <a-layout>
        <a-layout-content>
          <div class="nav">
            <span @click="ShowLoginModal" v-if="!isLogin">暂未登录</span>
            <span @click="LoginOut" v-if="isLogin">退出登录</span>
            <i class="iconfont icon-user iconStyle"></i>
          </div>
          <div :style="{ background: '#fff', minHeight: '360px' }" class="MapBox">
            <router-view @handleClickRain="showRainChart" @handleClickRiver="showlockStation" @closeChart="closeChart" />
          </div>
        </a-layout-content>
      </a-layout>
    </a-layout>
    <div class="echartBox" id="rainChart" v-show="visibleRainChart">
      <div class="echart"></div>
    </div>
    <div class="echartBox" id="riverChart" v-show="visibleRiverChart">
      <div class="echart"></div>
    </div>
    <div class="empty" v-show="visibleEmpty">
      <a-empty />
    </div>
    <a-modal v-model="loginModelVisible" title="登录" @ok="toLogin" @cancel="closeModal" cancelText="取消" okText="确认" style="z-index: 10000">
      <div class="inputCollection">
        <div class="inputItem">
          <span style="width: 100px">用户名:</span>
          <a-input v-model="username" placeholder="请输入用户名" id="name" />
        </div>
        <div class="inputItem">
          <span style="width: 100px">密码:</span>
          <a-input-password v-model="password" placeholder="请输入密码" id="password" />
        </div>
      </div>
    </a-modal>
  </div>
</template>
<script>
import "../assets/icon/iconfont.css";
import * as echarts from "echarts";
import { ref } from "vue";
export default {
  data() {
    return {
      isLogin: false,
      loginModelVisible: false,
      username: "",
      password: "",
      collapsed: ref(false),
      selectedKeys: ref(["1"]),
      visibleRainChart: false,
      visibleRiverChart: false,
      visibleEmpty: false,
      riverChart: [],
      rainChart: [],
    };
  },
  created() {
    if (this.$route.path == "/home/rainAggregate") {
      this.selectedKeys = ref(["2"]);
    } else if (this.$route.path == "/home/lockStation") {
      this.selectedKeys = ref(["3"]);
    } else {
      this.selectedKeys = ref(["1"]);
    }

    this.verifyToken();
  },
  computed: {
    showLoginNav: function () {
      return !(
        this.$route.path == "/home/rainAggregate" ||
        this.$route.path == "/home/lockStation"
      );
    },
  },
  mounted() {
    this.initEcharts();
    this.isLogin =
      localStorage.getItem("token") != null &&
      localStorage.getItem("token") != ""
        ? true
        : false;
  },
  methods: {
    // 如果是修改了token  是 200 此时token是失效的
    async verifyToken() {
      try {
        const { data: res } = await this.$http.get("/api/admin/verify");
        if (res.code != 200) {
          // token 添加多余的数字 --token失效
          // this.common.notify("warning", "权限失效,请重新登录");
          this.isLogin = false;
          localStorage.removeItem("token");
          this.selectedKeys = ref(["1"]);
          this.$router.push("/home/map");
        }
      } catch {
        //报错 说明token失效 为空时 触发
        // this.common.notify("warning", "权限失效,请重新登录");
        this.isLogin = false;
        localStorage.removeItem("token");
        this.selectedKeys = ref(["1"]);
        this.$router.push("/home/map");
      }
    },
    async toLogin() {
      const { data: res } = await this.$http.post("/api/admin/login", {
        username: this.username,
        password: this.password,
      });
      if (res.code == 200) {
        this.common.notify("success", "登录成功");
        // this.isLogin();
        localStorage.setItem("token", res.data.token);
        this.isLogin = true;
      } else {
        this.common.notify("warning", res.msg);
      }
      // 清空
      (this.username = ""),
        (this.password = ""),
        (this.loginModelVisible = false);
    },
    closeModal() {
      this.loginModelVisible = false;
    },
    ShowLoginModal() {
      this.loginModelVisible = true;
    },
    async LoginOut() {
      const { data: res } = await this.$http.get("/api/admin/logout");
      if (res.code == 200) {
        this.common.notify("success", "登出成功");
        this.isLogin = false;
        localStorage.removeItem("token");
        this.selectedKeys = ref(["1"]);
        this.$router.push("/home/map");
      }
    },
    // 初始化 雨量站图表
    initEcharts() {
      let rainOption = {
        title: {
          text: "",
          left: "center",
          textStyle: {
            color: "#000",
            fontWeight: "400",
            fontSize: "24",
            fontFamily: "Microsoft YaHei",
          },
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          name: "24小时内流量数据",
          nameTextStyle: {
            fontSize: 18 + "px",
            padding: [20, 0, 0, 0],
            color: "#000",
          },
          axisLabel: {
            interval: 0,
            fontSize: "10px",
          },
          nameLocation: "middle",
          data: [
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "10",
            "11",
            "12",
            "13",
            "14",
            "15",
            "16",
            "17",
            "18",
            "19",
            "20",
            "21",
            "22",
            "23",
            "24",
          ],
        },
        grid: {
          // containLabel:true,
          // left:50+'px',
          // right:50+'px',
          x: 80,
          y: 50,
          x2: 50,
          y2: 60,
          borderWidth: 10,
        },
        yAxis: {
          type: "value",
          axisLabel: {
            formatter: "{value} 毫米",
          },
          axisPointer: {
            snap: true,
          },
        },
        series: [
          {
            smooth: true,
            name: "流量",
            type: "line",
            label: {
              // show: true,
              formatter: (params) => {
                console.log(params);
                if (params.value != 0) {
                  return params.value.toFixed(2);
                } else return params.value;
              },
            },
            symbol: "circle",
          },
        ],
      };
      const rainChart = echarts.init(document.getElementById("rainChart")); // 图标初始化
      rainChart.setOption(rainOption); // 渲染页面
      this.rainChart = rainChart;
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        rainChart.resize();
      });
      // 初始化 河道站图表
      let riverOption = {
        title: {
          text: "",
          left: "center",
          textStyle: {
            color: "#000",
            fontWeight: "400",
            fontSize: "24",
            fontFamily: "Microsoft YaHei",
          },
        },
        tooltip: {
          trigger: "axis",
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          name: "24小时内流量数据",
          nameTextStyle: {
            fontSize: 18 + "px",
            padding: [20, 0, 0, 0],
            color: "#000",
          },
          axisLabel: {
            interval: 0,
            fontSize: "10px",
          },
          nameLocation: "middle",
          data: [
            "1",
            "2",
            "3",
            "4",
            "5",
            "6",
            "7",
            "8",
            "9",
            "10",
            "11",
            "12",
            "13",
            "14",
            "15",
            "16",
            "17",
            "18",
            "19",
            "20",
            "21",
            "22",
            "23",
            "24",
          ],
        },
        grid: {
          // containLabel:true,
          // left:50+'px',
          // right:50+'px',
          x: 80,
          y: 80,
          x2: 50,
          y2: 80,
          borderWidth: 10,
        },
        yAxis: {
           type: "value",
          axisLabel: {
            formatter: "{value} 立方米",
          },
          axisPointer: {
            snap: true,
          },
        },
        series: [
          {
             smooth: true,
            name: "流量",
            type: "line",
            label: {
              // show: true,
              formatter: (params) => {
                console.log(params);
                if (params.value != 0) {
                  return params.value.toFixed(2);
                } else return params.value;
              },
            },
          },
        ],
      };
      const riverChart = echarts.init(document.getElementById("riverChart")); // 图标初始化
      riverChart.setOption(riverOption); // 渲染页面
      this.riverChart = riverChart;
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        riverChart.resize();
      });
    },
    async showRainChart(event, id) {
      var date = new Date();
      var endTime = date.getHours();//endTime的范围在 0-23
      // console.log("当前时间", )
      let TimeList = [];
      for(let i =0;i<24;i++){
        TimeList.unshift(endTime);//往数组头上加
        endTime--;
        if(endTime<0){
          endTime+=24;
        }
    }
    console.log("Time",TimeList)
      const { data: res } = await this.$http.get(
        `/api/rainfall24hourdata/${id}`
      );
      if (!this.checkHaveData(res.code)) {
        this.visibleEmpty = true;
        return;
      }
      this.visibleRiverChart = false;
      this.visibleRainChart = true;
      var now = new Date(parseInt(res.data.timestamp));
      this.rainChart.setOption({
        title: {
          text:
            now.getMonth() +
            1 +
            "月" +
            now.getDate() +
            "日" +
            res.data.name +
            "雨量站",
        },
        xAxis: {
          name: "24小时内雨量数据",
          data:TimeList,
        },
        series: {
          data: res.data.pointData,
          symbol: "circle",
        },
      });
    },
    async showlockStation(e, id) {
       var date = new Date();
      var endTime = date.getHours();//endTime的范围在 0-23
      // console.log("当前时间", )
      let TimeList = [];
      for(let i =0;i<24;i++){
        TimeList.unshift(endTime);//往数组头上加
        endTime--;
        if(endTime<0){
          endTime+=24;
        }
    }
      const { data: res } = await this.$http.get(
        `/api/rivergateway24hourdata/${id}`
      );
      if (!this.checkHaveData(res.code)) {
        this.visibleEmpty = true;
        return;
      }
      var now = new Date(parseInt(res.data.timestamp));
      this.riverChart.setOption({
        title: {
          text:
            now.getMonth() +
            1 +
            "月" +
            now.getDate() +
            "日" +
            res.data.name +
            "站",
        },
        series: {
          data: res.data.pointData,
        },
        xAxis: {
          name: "24小时内雨量数据",
          data:TimeList,
        },
      });
      this.visibleRainChart = false;
      this.visibleRiverChart = true;
    },
    closeChart(e) {
      this.visibleRainChart = false;
      this.visibleEmpty = false;
      this.visibleRiverChart = false;
      // console.log(e.lnglat.lat,e.lnglat.lng)
    },
    // 如果这个站点的数据后台是没有的 则进行处理
    checkHaveData(code) {
      return code == 200;
    },
    // BUG点: 数字类型 到了小数点后6位 就会自动四舍五入
  },
};
</script>
<style scoped>
.logo {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 50px;
  font-weight: 550;
  font-size: 18px;
  color: #fff;
  background-color: #03a9f4;
}

.site-layout .site-layout-background {
  background: #fff;
}
[data-theme="dark"] .site-layout .site-layout-background {
  background: #141414;
}
.ant-menu-dark.ant-menu-inline .ant-menu-item,
.ant-menu-dark.ant-menu-vertical .ant-menu-item,
.ant-menu-dark.ant-menu-vertical-left .ant-menu-item,
.ant-menu-dark.ant-menu-vertical-right .ant-menu-item {
  display: flex;
  justify-content: center;
}
.ant-layout-sider {
  background-color: #273238;
}
.ant-menu-dark,
.ant-menu-dark .ant-menu-sub {
  background-color: #273238;
}
div /deep/ .ant-layout-sider-trigger {
  background: #273238;
}

.empty {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  width: 700px;
  height: 290px;
  z-index: 999;
  text-align: center;
  border-radius: 20px;
  padding-top: 10px;
  border: 1px solid #bdbdbd;
  background: #fff;
  transform: translate(-50%, -50%);
  left: calc(50% + 100px);
  top: 50%;
}
.echartBox {
  display: flex;
  justify-content: center;
  align-items: center;
  position: absolute;
  width: 700px;
  height: 290px;
  z-index: 999;
  text-align: center;
  border-radius: 20px;
  padding-top: 10px;
  border: 1px solid #bdbdbd;
  background: #fff;
  transform: translate(-50%, -50%);
  left: calc(50% + 100px);
  top: 50%;
}
.ant-menu-vertical .ant-menu-item,
.ant-menu-vertical-left .ant-menu-item,
.ant-menu-vertical-right .ant-menu-item,
.ant-menu-inline .ant-menu-item,
.ant-menu-vertical .ant-menu-submenu-title,
.ant-menu-vertical-left .ant-menu-submenu-title,
.ant-menu-vertical-right .ant-menu-submenu-title,
.ant-menu-inline .ant-menu-submenu-title {
  margin-top: 0;
}

.ant-layout,
.ant-layout * {
  overflow: hidden;
}
.ant-menu-item .anticon,
.ant-menu-submenu-title .anticon {
  display: flex;
  justify-content: center;
}
.iconStyle {
  width: 30px;
  display: flex;
  justify-content: flex-start;
}
.nav {
  height: 50px;
  width: 100%;
  background: #fff;
  display: flex;
  align-content: center;
  /* justify-content: center; */
  align-items: center;
  padding-right: 20px;
  flex-direction: row-reverse;
}
.MapBox {
  height: calc(100% - 50px);
}
.inputItem {
  display: flex;
  align-items: center;
  width: 350px;
  margin-bottom: 30px;
}
.inputCollection {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-content: center;
}
</style>
